<?php

namespace App\Http\Controllers\API;

use App\Models\DayCollection;
use App\Models\EnterCarFlow;
use App\Models\FlowCollection;
use App\Models\ParkRecord;
use App\Models\PayFee;
use App\Models\ParkInfo;
use App\Models\Video;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use App\Models\LiftPole;
use Illuminate\Support\Facades\DB;

class ScreenController extends AppBaseController
{

    /**
     * 数据投屏总量
     * ＠mock
     * {
        "success": true,
        "data": {
        "pay_src_amount": "13955",
        "pay_amount": "13955",
        "charge_number": "12",
        "leave_flow": "264",
        "enter_leave": "53",
        "inner_car": 7442
        },
        "message": "请求成功"
        }
     * @param Request $request
     * @return mixed
     */
    public function total(Request $request)
    {
        $this->validate($request, ['park_code' => 'required']);
        $data = [];
        $today = Carbon::today();
        $tomorrow= Carbon::tomorrow();
        $park_code = $request->get('park_code');
        //免费抬干
        $freeCarCharge = LiftPole::where('out_time', '>=', $today->getTimestamp())
            ->where('out_time', '<', $tomorrow->getTimestamp())
            ->sum('calc_charge');

        //交易情况查询
        $charge = PayFee::where('pay_time', '>=', $today->getTimestamp())
            ->where('pay_time', '<',$tomorrow->getTimestamp())
            ->whereIn('park_code', $park_code)
            ->first([
                \DB::raw('IFNULL(SUM(pay_src_amount),0)as pay_src_amount'),
                \DB::raw('IFNULL(SUM(pay_amount),0) as pay_amount'),
                \DB::raw('IFNULL(SUM(1),0)  as charge_number')
            ]);

        $data['pay_src_amount'] = $charge->pay_src_amount + $freeCarCharge;
        $data['pay_amount'] = $charge->pay_amount;
        $data['charge_number'] = $charge->charge_number;



        //出场流量
        $data['leave_flow'] = FlowCollection::where('hour', '>=', $today)
            ->whereIn('park_code', $park_code)
            ->where('hour', '<', $tomorrow)
            ->sum('leave_flow');

        //进场流量
        $data['enter_leave'] = EnterCarFlow::where('hour', '>=', $today)
            ->where('hour', '<', $tomorrow)
            ->whereIn('park_code', $park_code)
            ->sum('flow');

        //在场车
        $data['inner_car'] = ParkRecord::leaveFlow($park_code)->sum('inner_park');
        $data['time'] = date("Y-m-m H:i:s");

       return $this->sendResponse($data,'请求成功');

    }

    public function timeTotal(Request $request)
    {
        $this->validate($request, ['park_code' => 'required']);
        $time = date("Y-m-d H:i:s");
        $data = [];
        $today = Carbon::today();
        $tomorrow= Carbon::tomorrow();
        $carType = config('custom.pay_type');
        $park_code = $request->get('park_code');
        //免费抬干
        $freeCarCharge = LiftPole::where('out_time', '>=', $today->getTimestamp())
            ->where('out_time', '<', $tomorrow->getTimestamp())
            ->sum('calc_charge');

        //交易情况查询
        $charge = PayFee::where('pay_time', '>=', $today->getTimestamp())
            ->where('pay_time', '<',$tomorrow->getTimestamp())
            ->whereIn("pay_type",$carType)
            ->whereIn('park_code', $park_code)
            ->first([
                \DB::raw('IFNULL(SUM(pay_src_amount),0)as pay_src_amount'),
                \DB::raw('IFNULL(SUM(pay_amount),0) as pay_amount'),
                \DB::raw('IFNULL(SUM(1),0)  as charge_number')
            ]);

        $data['pay_src_amount'] = $charge->pay_src_amount + $freeCarCharge;
        $data['pay_amount'] = $charge->pay_amount;
        $data['charge_number'] = $charge->charge_number;

        if(in_array("7100000288", $park_code)){
            foreach ($park_code as $k=>$v) {
                if($v == "7100000290" || $v == "7100000291"){
                    unset($park_code[$k]);
                }
            }
        }

        //进场流量
        $data['leave_flow'] = FlowCollection::where('hour', '>=', $today)
            ->whereIn('park_code', $park_code)
            ->where('hour', '<', $tomorrow)
            ->sum('leave_flow');

        //出场流量
        $data['enter_leave'] = EnterCarFlow::where('hour', '>=', $today)
            ->where('hour', '<', $tomorrow)
            ->whereIn('park_code', $park_code)
            ->sum('flow');

        $data['time'] = $time;

        return $this->sendResponse($data,'请求成功');

    }

    function nowParkCount(Request $request){
        $this->validate($request, ['park_code' => 'required']);
        $data = [];
        $park_code = $request->get('park_code');

        $parks = ParkInfo::whereIn("park_code", $park_code)
                        ->select("space_total", 'space_empty',"park_code")
                        ->get();
        
        $data['inner_car'] = 0;
        foreach ($parks as $park) {
            $inner_car = $inner_park = $park->space_total - $park->space_empty;
            $inner_car = $inner_park > 0 ? $inner_park : 0;
            $data['inner_car'] += $inner_car;
        }

        //在场车
        // $data['inner_car'] = ParkRecord::leaveFlow($park_code)->sum('inner_park');

        return $this->sendResponse($data,'请求成功');
    }

    /**
     * 当天车场流量
     *
     * @param Request $request
     * @return mixed
     */
    public function range(Request $request)
    {
        $this->validate($request, ['park_code' => 'required']);

        $today = Carbon::today();
        $tomorrow= Carbon::tomorrow();
        $park_code = $request->get('park_code');

        $data = DayCollection::whereIn('park_code',$park_code)
            ->where('hour', '>=', $today)
            ->where('hour', '<', $tomorrow)
            ->select([
                    'hour',
                    'park_code',
                    'leave_flow',
                    'enter_flow',
                    'all_flow',
                ]
            )->get();
        // 获取车场总数
        $space_arr = ParkInfo::whereIn('park_code',$park_code)->select(["space_total","space_empty","park_code"])->get();
        foreach ($space_arr as &$val) {
            $num = $val->space_total>0?round(($val->space_total-$val->space_empty)/$val->space_total,2)*100:'0';
            $val->per = $val->space_total>0?($num>100?'100':$num)."%":'0%';
        }
        $space_arr = obj2arr($space_arr);
        $park_per_arr = array_column($space_arr,"per","park_code");
        foreach ($data as &$val) {
            if(isset($park_per_arr[$val->park_code])) {
                $val->per = $park_per_arr[$val->park_code];
            } else {
                $val->per = '0%';
            }
        }

        $data = $data->groupBy('park_code')->toArray();

        return $this->sendResponse($data,'请求成功');
    }

    /**
     * 线上支付对账 明细
     *
     * @param Request $request
     * @return mixed
     */
    public function payTypePer(Request $request)
    {
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;

        $pay_type = config('custom.pay_type');
        $pay_name= config('custom.pay_name');

        // 获取车场记录
        $p = new PayFee();

        // 获取车场范围
//        $p = $p->whereIn("park_code", $this->park_arr);

        $date = date("Y-m-d");
        // 支付时间
        $p = $p->where("pay_time", '>=', strtotime($date.' 00:00:00'));
        $p = $p->where("pay_time", '<=', strtotime($date.' 23:59:59'));
        $p = $p->whereIn("pay_type",$pay_type);
        $res = $p->select([
            'pay_type',
            \DB::raw("SUM(pay_src_amount) as amount"),
            \DB::raw("count(1) as count"),
        ])->groupBy("pay_type")->get();
        $res_amount_per = [];
        $res_count_per = [];
        $data['count'] = [];
        $data['amount'] = [];
        if($res){
            $res = $res->toArray();
            $res_count = array_column($res, "count","pay_type");
            $total_count = array_sum($res_count);
            $res_amount = array_column($res, "amount","pay_type");
            $total_amount = array_sum($res_amount);
            foreach ($pay_type as $re) {
                if(!isset($res_count[$re])){
                    $res_count[$re] = 0;
                }

                $data['count'][] = ['name'=>$pay_name[$re],'value'=>$res_count[$re]];
                if(!isset($res_amount[$re])){
                    $res_amount[$re] = '0';
                }
                $data['amount'][] = ['name'=>$pay_name[$re],'value'=>$res_amount[$re]];
            }
        } else {
            foreach ($pay_type as $re) {
                $data['count'][] = ['name'=>$pay_name[$re],'value'=>0];
                $data['amount'][] = ['name'=>$pay_name[$re],'value'=>0];
            }
        }
        return $this->sendResponse($data, '查询成功');
    }

    function importData(Request $request){
        $file = storage_path();
        $file = $file."/bb.csv";
        $fp = fopen($file,'r');
        $res = [];
        while(!feof($fp)){
            $data = fgets($fp,4096);
            $arr = explode(',',$data);
            if(empty($arr[7])) continue;
            if(empty($arr[6])) continue;
            $insert_data = [];
            $insert_data['camera_index'] = $arr[0];
            $insert_data['camera_name'] = $arr[1];
            $insert_data['camera_type'] = $arr[2];
            $insert_data['camera_device_id'] = $arr[3];
            $insert_data['location'] = 'CVR存储'; //$arr[4];
            $insert_data['park_code'] = $arr[6];
            $insert_data['arm_code'] = $arr[7];
            $insert_data['device_type'] = isset($arr[8])&&is_numeric($arr[8])?$arr[8]:0;
            $insert_data['gate_type'] = is_numeric(trim($arr[9],"\r\n"))?trim($arr[9],"\r\n"):0;
            $res[] = $insert_data;
        }

        DB::table('video_config')->insert($res);

        echo 11; exit;
        fclose($fp);
    }

}
